from rest_framework import serializers
from goods.models import SKU

class CartSerializer(serializers.Serializer):
    sku_id = serializers.CharField(label='商品id', required=True)
    count = serializers.IntegerField(label='个数', required=True, min_value=1)
    selected = serializers.BooleanField(label='是否选项', default=True, required=False)

    def validate(self, attrs):
        sku_id = attrs['sku_id']
        count = attrs.get('count')
        #1.判断商品是否存在
        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品信息不存在')
        #2.判断库存
        if count > sku.stock:
            raise serializers.ValidationError('库存不足')
        return attrs
        #data---attrs---validated_data

class CartSKUSerializer(serializers.ModelSerializer):
    count = serializers.IntegerField(label='数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')

class CartDeleteSerializer(serializers.Serializer):
    sku_id = serializers.CharField(label='id',required=True)
    def validate(self, attrs):
        sku_id = attrs['sku_id']
        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品信息不存在')
        return attrs